package com.aitangbao.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.aitangbao.core.dto.BootTablePage;
import com.aitangbao.core.mapper.KCategoryDao;
import com.aitangbao.core.model.KCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CategoryService {
    @Autowired
    private KCategoryDao kCategoryDao;
  
    public List<KCategory> getList(Integer uId){
        List<KCategory> resultList = new ArrayList<KCategory>();
        QueryWrapper<KCategory> queryWrapper = new QueryWrapper<KCategory>();
        queryWrapper.eq("add_user", uId);
        resultList.addAll(kCategoryDao.selectList(queryWrapper));
        return resultList;
    }
    
    public BootTablePage getList(Integer start, Integer size, Integer uId){
        //根据当前数量求页数
        if (start != null && size !=null) {
            start = start/size + 1;
        }
        Page page = new Page(start, size);
        IPage<KCategory> iPage = kCategoryDao.selectPage(page, new QueryWrapper<KCategory>().eq("add_user",uId));
        BootTablePage bootTablePage = new BootTablePage();
        bootTablePage.setRows(iPage.getRecords());
        bootTablePage.setTotal(iPage.getTotal());
        return bootTablePage;
    }
 
    public KCategory getQuartz(Integer categoryId){
        return kCategoryDao.selectById(categoryId);
    }
    
    public void insert(KCategory kCategory, Integer uId){
        kCategory.setAddTime(new Date());
        kCategory.setAddUser(uId);
        kCategory.setEditTime(new Date());
        kCategory.setEditUser(uId);
        kCategory.setDelFlag(1);
        kCategoryDao.insert(kCategory);
    }

    public void delete(Integer categoryId){
        kCategoryDao.deleteById(categoryId);
    }

 
    public void update(KCategory kCategory, Integer uId){
        kCategory.setEditTime(new Date());
        kCategory.setEditUser(uId);
        //只有不为null的字段才参与更新
        kCategoryDao.updateById(kCategory);
    }

    public boolean IsCategoryExist(Integer categoryId,String categoryName) {
        QueryWrapper<KCategory> queryWrapper = new QueryWrapper<KCategory>();
        queryWrapper.eq("category_name", categoryName);
        KCategory category = kCategoryDao.selectOne(queryWrapper);
        if (null == category) {
            return false;
        } else if(categoryId!=null&&category.getCategoryId()==categoryId){
            return false;
        }else{
            return true;
        }
    }
}
